import os
import re
import device

def scan(ifname):
    # Some debugging stuff
    live = True
    if live:
        a = os.popen("iwlist " + ifname + " scanning")
        lines = a.read().strip().split('\n')
        a.close()
    else:
        a = open('n800-aps.txt')
        lines = a.read().strip().split('\n')
        a.close()

    current = -1
    aps = []

    while lines:
        if current > -1:
            ap = aps[current] 
        line = lines[0]

        mac = re.compile("[ ]+Cell [0-9]+ - Address: (?P<mac>[\w:]+)")
        macmatch = mac.match(line)
        if macmatch:
            ap = {}
            ap['mac'] = macmatch.groups('mac')[0]
            aps.append(ap)
            current += 1
            lines = lines[1:]
            continue

        essid = re.compile("[ ]+ESSID:\"(?P<essid>[\w\s\.]*)\"")
        essidmatch = essid.match(line)
        if essidmatch:
            ap['essid'] = essidmatch.group('essid')
            lines = lines[1:]
            continue
        
        if device.current_device() == device.NOKIA_TABLET:
            signal = re.compile(".*Signal level:(?P<level>-\d+) dBm")
        else:
            signal = re.compile(".*Signal level=(?P<level>-\d+) dBm")

        signalmatch = signal.match(line)

        if signalmatch:
            ap['level'] = signalmatch.group('level')
            lines = lines[1:]
            continue
        
        enc = re.compile("[ ]+Encryption key:(?P<encryption>[\w]*)")
        encmatch = enc.match(line)
        
        if encmatch:
            encrypted = encmatch.group('encryption').trim()
            if encrypted == 'off':
                encrypted = False
            else:
                encrypted = True
            ap['encryption'] = encrypted
            lines = lines[1:]
            continue
        
        lines = lines[1:]
    
    return aps

if __name__ == '__main__':
     # Sort by level
    aps = scan('eth1')
    from operator import itemgetter
    aps = sorted(aps, key= itemgetter('level'))

    # Filter ML only
    ml_re = re.compile("media lab 802\.11")
    def ml_filter(x):
        if 'essid' in x:
            return ml_re.match(x['essid']) != None
        else:
            return False
      
    print filter(ml_filter, aps)
